#!/usr/bin/env bash

#
# Build php in WSL(Debian Ubuntu)
#
# $ lnmp-wsl-php-builder 5.6.35 [--skipbuild] [tar] [deb] [--ci] [arm64] [arm32]
#

# help info

_print_help_info(){

    echo "
Build php in WSL Debian by shell script

Usage:

$ lnmp-wsl-builder-php 7.3.0 7.3.0beta1 7.3.0RC1 nightly

$ lnmp-wsl-builder-php [ apt | apt-dev ]

$ lnmp-wsl-builder-php 7.3.0 [ tar | deb ] [--skipbuild] [--ci]

# echo \"--with-xxx --enable-xxx\" > /tmp/EXT_REAL_NAME.configure.options
$ lnmp-wsl-builder-php 7.3.0 enable-ext [EXT_NAME@EXT_REAL_NAME]

$ lnmp-wsl-builder-php 7.3.0 [ arm64 | arm32 ] tar [TODO]

"

exit 0

}

################################################################################

_sudo(){
  command -v sudo > /dev/null && echo "sudo" || true
}

command -v apt > /dev/null

if ! [ 0 -eq $? ];then echo "Only Support Debian"; exit ; fi

source /etc/os-release

################################################################################

PHP_TIMEZONE=PRC
PHP_URL=https://www.php.net/distributions
PHP_GIT=https://github.com/php/php-src

host=x86_64-linux-gnu

if [ "${LNMP_CN_ENV}" != 'false' ];then
  PHP_URL=https://mirrors.sohu.com/php
  PHP_GIT=https://github.com.cnpmjs.org/php/php-src
fi

PHP_INSTALL_LOG=/tmp/php-builder/$(date +%s).install.log

export COMPOSER_VERSION=2.0.8
export COMPOSER_ALLOW_SUPERUSER=1
export COMPOSER_HOME=/tmp/composer
export TZ=Asia/Shanghai
# export CC=clang CXX=clang
export CC=gcc CXX=g++
################################################################################

for command in "$@"
do
test $command = 'arm64' && host=aarch64-linux-gnu
test $command = 'arm32' && host=arm-linux-gnueabihf
done

test $host = 'aarch64-linux-gnu' && \
              export CC=aarch64-linux-gnu-gcc \
                     CXX=aarch64-linux-gnu-g++ \
                     armMake="ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu-"

test $host = 'arm-linux-gnueabihf' && \
              export CC=arm-linux-gnueabihf-gcc \
                     CXX=arm-linux-gnueabihf-g++ \
                     armMake="ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-"

################################################################################

#
# https://github.com/docker-library/php/issues/272
#

PHP_CFLAGS="-fstack-protector-strong -fpic -fpie -O2"
PHP_CPPFLAGS="$PHP_CFLAGS"
PHP_LDFLAGS="-Wl,-O1 -pie"

################################################################################

_get_phpnum(){

case "$1" in
  5.6.* )
    export PHP_NUM=56
    ;;

  7.0.* )
    export PHP_NUM=70
    ;;

  7.1.* )
    export PHP_NUM=71
    ;;

  7.2.* )
    export PHP_NUM=72
    ;;

  7.3.* )
     export PHP_NUM=73
     ;;

  7.4.* )
     export PHP_NUM=74
     ;;

  8.0.* )
     export PHP_NUM=80
     ;;

  8.1.* )
     export PHP_NUM=81
     export BUILD_FROM_GIT=1
     export PHP_SRC_BRANCH=PHP-8.1
     ;;

  nightly )
    export PHP_NUM=81
    export BUILD_FROM_GIT=1
    ;;

  * )
    echo "ONLY SUPPORT 5.6 7.0 7.1 7.2 7.3 7.4 8.0 nightly"
    exit 1
esac
}

################################################################################

# download php src

_download_src(){
    $(_sudo) mkdir -p /usr/local/src
    $(_sudo) chmod -R 777 /usr/local/src

    if ! [ -z "$BUILD_FROM_GIT" ];then
      $(_sudo) apt install bison git -y

      git clone --depth=1 -b ${PHP_SRC_BRANCH:-master} ${PHP_GIT} /usr/local/src/php-${PHP_VERSION} || \
        ( git -C /usr/local/src/php-${PHP_VERSION} fetch --depth=1 origin master ; \
          git -C /usr/local/src/php-${PHP_VERSION} reset --hard origin/master ;
        )

      return
    fi

    if ! [ -d /usr/local/src/php-${PHP_VERSION} ];then

        echo -e "Download php src ...\n\n"

        cd /usr/local/src ; $(_sudo) chmod 777 /usr/local/src

        wget ${PHP_URL}/php-${PHP_VERSION}.tar.gz

        echo -e "Untar ...\n\n"

        tar -zxvf php-${PHP_VERSION}.tar.gz > /dev/null 2>&1
    fi
}

################################################################################

# install packages

_build_arm_php_build_dep(){
################################################################################

  DEP_PREFIX=/opt/${host}

  ZLIB_VERSION=1.2.11
  LIBXML2_VERSION=2.9.8

################################################################################

_buildlib(){
  if [ -f /opt/${host}/$LIB_NAME ];then return 0 ; fi

  cd /tmp ; test ! -d $TAR_FILE && ( wget $URL ; tar -zxvf $TAR )

  cd $TAR_FILE && ./configure $CONFIGURES && make && $(_sudo) make install
}

################################################################################

LIB_NAME=
URL=
TAR=
TAR_FILE=
CONFIGURES="--prefix=${DEP_PREFIX}/zlib"
# _buildlib

################################################################################

LIB_NAME=zlib/lib/libz.so.${ZLIB_VERSION}
URL=http://www.zlib.net/zlib-${ZLIB_VERSION}.tar.gz
TAR=zlib-${ZLIB_VERSION}.tar.gz
TAR_FILE=zlib-${ZLIB_VERSION}
CONFIGURES="--prefix=${DEP_PREFIX}/zlib"
_buildlib

################################################################################

command -v python-config > /dev/null || pip install python-config

LIB_NAME=libxm2/lib/libxml2.so.${LIBXML2_VERSION}
URL=ftp://xmlsoft.org/libxml2/libxml2-${LIBXML2_VERSION}.tar.gz
TAR=libxml2-${LIBXML2_VERSION}.tar.gz
TAR_FILE=libxml2-${LIBXML2_VERSION}
CONFIGURES="--prefix=${DEP_PREFIX}/libxm2 \
                        --host=${host} \
                        --with-zlib=${DEP_PREFIX}/zlib \
                        --with-python=/tmp/$TAR_FILE/python"
_buildlib

################################################################################

}

buster_pkg(){
  if ! [ "${VERSION_CODENAME}" = 'buster' ];then
    return
  fi

  echo ""
}

stretch_pkg(){
  if ! [ "${VERSION_CODENAME}" = 'stretch' ];then
    return
  fi

  echo ""
}

ubuntu_xenial_pkg(){
  if ! [ "${UBUNTU_CODENAME}" = 'xenial' ];then
    return
  fi

  echo ""
}

ubuntu_bionic_pkg(){
  if ! [ "${UBUNTU_CODENAME}" = 'xenial' ];then
    return
  fi

  echo ""
}

_test_pkg(){
  $(_sudo) apt install -y $1 > /dev/null 2>&1 && echo $1 || true
}

_install_php_run_dep(){

    test $host != 'x86_64-linux-gnu' && _build_arm_php_build_dep && return 0

    export PHP_RUN_DEP="libedit2 \
zlib1g \
libxml2 \
openssl \
libsqlite3-0 \
libxslt1.1 \
libpq5 \
libmemcached11 \
libmemcachedutil2 \
libsasl2-2 \
libfreetype6 \
libpng16-16 \
$( $(_sudo) apt install -y libjpeg62-turbo > /dev/null 2>&1 && echo libjpeg62-turbo ) \
$( $(_sudo) apt install -y libjpeg-turbo8 > /dev/null 2>&1 && echo libjpeg-turbo8 ) \
$( if [ $PHP_NUM -ge "72" ];then \
     echo $( if ! [ "${ARGON2}" = 'false' ];then \
               echo "libargon2-0";
             fi ); \
     echo $( $(_sudo) apt install -y libsodium18 > /dev/null 2>&1 && echo libsodium18) ;\
     echo $( $(_sudo) apt install -y libsodium23 > /dev/null 2>&1 && echo libsodium23) ;\
     echo $( $(_sudo) apt install -y libzip4 > /dev/null 2>&1 && echo libzip4) ;\
     echo $( $(_sudo) apt install -y libzip5 > /dev/null 2>&1 && echo libzip5) ;\
   fi ) \
libyaml-0-2 \
libbz2-1.0 \
libexif12 \
libgmp10 \
libc-client2007e \
libkrb5-3 \
libxpm4 \
$( $(_sudo) apt install -y libwebp5 > /dev/null 2>&1 && echo libwebp5 ) \
$( $(_sudo) apt install -y libwebp6 > /dev/null 2>&1 && echo libwebp6 ) \
$( _test_pkg libenchant1c2a ) \
$( _test_pkg libenchant-2-2 ) \
libssl1.1 \
$( $(_sudo) apt install -y libicu55 > /dev/null 2>&1 && echo libicu55) \
$( $(_sudo) apt install -y libicu57 > /dev/null 2>&1 && echo libicu57) \
$( $(_sudo) apt install -y libicu60 > /dev/null 2>&1 && echo libicu60) \
$( $(_sudo) apt install -y libicu63 > /dev/null 2>&1 && echo libicu63) \
libldap-2.4-2 \
$( $(_sudo) apt install -y libffi6 > /dev/null 2>&1 && echo libffi6) \
$( $(_sudo) apt install -y libffi7 > /dev/null 2>&1 && echo libffi7) \
$( $(_sudo) apt install -y libonig4 > /dev/null 2>&1 && echo libonig4) \
$( $(_sudo) apt install -y libonig5 > /dev/null 2>&1 && echo libonig5) \
libc6 \
tzdata \
"

# $( $(_sudo) apt install -y libtidy-0.99-0 > /dev/null 2>&1 && echo libtidy-0.99-0 ) \
# $( $(_sudo) apt install -y libtidy5 > /dev/null 2>&1 && echo libtidy5 ) \
# $( $(_sudo) apt install -y libtidy5deb1 > /dev/null 2>&1 && echo libtidy5deb1 ) \

    $(_sudo) apt install -y $PHP_RUN_DEP > /dev/null
}

################################################################################

_install_php_build_dep(){
    export DEP_SOFTS="autoconf \
                   curl \
                   lsb-release \
                   dpkg-dev \
                   file \
                   $( test ${CC:-gcc} = 'gcc'  && echo "gcc g++ libc6-dev" ) \
                   $( test "$CC" = 'clang'     && echo "clang" ) \
                   $( test "$host" = 'aarch64-linux-gnu'    && echo "gcc-aarch64-linux-gnu g++-aarch64-linux-gnu" ) \
                   $( test "$host" = 'arm-linux-gnueabihf'  && echo "gcc-arm-linux-gnueabihf g++-arm-linux-gnueabihf" ) \
                   make \
                   pkg-config \
                   re2c \
                   libedit-dev \
                   zlib1g-dev \
                   libxml2-dev \
                   libssl-dev \
                   libsqlite3-dev \
                   libxslt1-dev \
                   libcurl4-openssl-dev \
                   libpq-dev \
                   libmemcached-dev \
                   libsasl2-dev \
                   libfreetype6-dev \
                   libpng-dev \
                   $( $(_sudo) apt install -y libjpeg62-turbo-dev > /dev/null 2>&1 && echo libjpeg62-turbo-dev ) \
                   $( $(_sudo) apt install -y libjpeg-turbo8-dev > /dev/null 2>&1 && echo libjpeg-turbo8-dev ) \
                   \
                   $( test $PHP_NUM = "56" && echo "" ) \
                   $( test $PHP_NUM = "70" && echo "" ) \
                   $( test $PHP_NUM = "71" && echo "" ) \
                   $( if [ $PHP_NUM -ge "72" ];then \
                        echo "libsodium-dev libzip-dev"; \
                      fi ) \
                      \
                   libyaml-dev \
                   libbz2-dev \
                   libexif-dev \
                   libgmp-dev \
                   libc-client2007e-dev \
                   libkrb5-dev \
                   \
                   libxpm-dev \
                   libwebp-dev \
                   $( _test_pkg libenchant-dev ) \
                   $( _test_pkg libenchant-2-dev ) \
                   libldap2-dev \
                   libpspell-dev \
                   libicu-dev \
                   libffi-dev \
                   libonig-dev \
                   "
                  #  libtidy-dev \
    for soft in ${DEP_SOFTS} ; do echo $soft | tee -a ${PHP_INSTALL_LOG} ; done

    $(_sudo) apt install -y --no-install-recommends ${DEP_SOFTS}
}

################################################################################

_test(){
    ${PHP_PREFIX}/bin/php -v

    ${PHP_PREFIX}/bin/php -i | grep .ini

    ${PHP_PREFIX}/sbin/php-fpm -v

    set +x
    for ext in `ls /usr/local/src/php-${PHP_VERSION}/ext`; \
    do echo '*' $( ${PHP_PREFIX}/bin/php -r "if(extension_loaded('$ext')){echo '[x] $ext';}else{echo '[ ] $ext';}" ); done
    set -x
}


################################################################################

_builder(){

# fix bug

   export gnuArch="$(dpkg-architecture --query DEB_BUILD_GNU_TYPE)"
   debMultiarch="$(dpkg-architecture --query DEB_BUILD_MULTIARCH)"

_fix_bug(){
#
# https://bugs.php.net/bug.php?id=74125
#

    if [ ! -d /usr/include/curl ]; then
    $(_sudo) ln -sTf "/usr/include/$debMultiarch/curl" /usr/local/include/curl
    fi

#
# https://stackoverflow.com/questions/34272444/compiling-php7-error
#

    $(_sudo) ln -sf /usr/lib/libc-client.so.2007e.0 /usr/lib/$debMultiarch/libc-client.a

#
# debian 9 php56 configure: error: Unable to locate gmp.h
#

    $(_sudo) ln -sf /usr/include/$debMultiarch/gmp.h /usr/include/gmp.h

#
# https://stackoverflow.com/questions/43617752/docker-php-and-freetds-cannot-find-freetds-in-know-installation-directories
#

    # $(_sudo) ln -sf /usr/lib/x86_64-linux-gnu/libsybdb.so /usr/lib/

#
# configure: error: Cannot find ldap libraries in /usr/lib.
#
# @link https://blog.csdn.net/ei__nino/article/details/8598490

    $(_sudo) cp -frp /usr/lib/$debMultiarch/libldap* /usr/lib/
}

test $host = 'x86_64-linux-gnu'  && _fix_bug

################################################################################
set +e
# configure
    CONFIGURE="--prefix=${PHP_PREFIX} \
      --sysconfdir=${PHP_INI_DIR} \
      \
      --build="$gnuArch" \
      --host=${host:-x86_64-linux-gnu} \
      \
      --with-config-file-path=${PHP_INI_DIR} \
      --with-config-file-scan-dir=${PHP_INI_DIR}/conf.d \
      --enable-fpm \
      --with-fpm-user=nginx \
      --with-fpm-group=nginx \
      \
      --with-curl \
      --with-gettext \
      --with-kerberos \
      --with-libedit \
      --with-openssl \
        --with-system-ciphers \
      --with-pdo-mysql \
      --with-pdo-pgsql=shared \
      --with-xsl=shared \
      --with-zlib \
      --with-mhash \
          $( test $PHP_NUM -ge "74" && \
            echo "--enable-gd=shared \
                    --with-freetype \
                    --with-jpeg \
                    --with-webp \
                    --with-xpm \
                    --with-ffi=shared \
                    --with-zip" \
            || echo "--with-pcre-regex \
                     --with-gd=shared \
                       --with-freetype-dir=/usr/lib \
                       --with-jpeg-dir=/usr/lib \
                       --with-png-dir=/usr/lib \
                       --with-xpm-dir=/usr/lib \
                       --enable-zip") \
        --disable-gd-jis-conv \
      --enable-ftp \
      --enable-mysqlnd \
      --enable-bcmath \
      --enable-mbstring \
      --enable-pcntl=shared \
      --enable-soap=shared \
      --enable-sockets=shared \
      --enable-sysvmsg=shared \
      --enable-sysvsem=shared \
      --enable-sysvshm=shared \
      --enable-calendar=shared \
      --enable-intl=shared \
      --enable-embed=shared \
      --enable-option-checking=fatal \
      --with-mysqli=shared \
      --with-pgsql=shared \
    \
    $( test $PHP_NUM = "56" && echo "--enable-opcache --enable-gd-native-ttf" ) \
    $( test $PHP_NUM = "70" && echo "--enable-gd-native-ttf --with-webp-dir=/usr/lib" ) \
    $( test $PHP_NUM = "71" && echo "--enable-gd-native-ttf --with-webp-dir=/usr/lib" ) \
    \
    $( if [ $PHP_NUM -ge "72" ];then \
         echo $( if ! [ "${ARGON2}" = 'false' ];then \
                   echo "--with-password-argon2"; \
                 fi ); \
         echo "--with-sodium \
               --with-pcre-jit"; \
         if [ $PHP_NUM -lt "74" ];then \
           echo "--with-webp-dir=/usr/lib --with-libzip"; \
         fi; \
       fi ) \
      --enable-exif \
      --with-bz2 \
      --with-gmp \
      --with-imap=shared \
          --with-imap-ssl \
      \
      --with-pic \
      --with-enchant=shared \
      --enable-fileinfo=shared \
      --with-ldap=shared \
          --with-ldap-sasl \
      --with-pspell=shared \
      --enable-shmop=shared \
      $( test "$host" != 'x86_64-linux-gnu' && echo "--with-libxml-dir=/opt/${host}/libxml2 \
                                                     --with-zlib-dir=/opt/${host}/zlib" ) \
      "

      # --with-tidy \
    set -e

    for item in ${CONFIGURE}; do echo $item | tee -a ${PHP_INSTALL_LOG}; done

    cd /usr/local/src/php-${PHP_VERSION}

    export CFLAGS="$PHP_CFLAGS"
    export CPPFLAGS="$PHP_CPPFLAGS"
    export LDFLAGS="$PHP_LDFLAGS"

    buster_patch(){
      if ! [ "${VERSION_CODENAME}" = 'buster' ];then
        return
      fi

      if [ "${PHP_NUM}" -le "73" ];then
        curl -O https://salsa.debian.org/php-team/php/raw/debian/7.3.9-1/debian/patches/0047-Use-pkg-config-for-FreeType2-detection.patch
        patch -p1 < 0047-Use-pkg-config-for-FreeType2-detection.patch
        ./buildconf --force
      fi
    }

    sid_php74_with_enchant2_patch(){
      # sid only include libenchant-2-2
      local libenchant2_exists=$(_test_pkg libenchant-2-2)

      if [ "${PHP_NUM}" -lt "74" -a -n "$libenchant2_exists" ];then
        echo "this os only include libenchant-2-2, PHP 7.3- can't build with libenchant-2-2"

        exit 1
      fi

      if [ "${PHP_NUM}" -ne "74" ];then return; fi

      if [ -n "$libenchant2_exists" ];then
        curl -O https://salsa.debian.org/php-team/php/-/raw/debian/main/7.4/debian/patches/0040-remove-deprecated-call-and-deprecate-function-to-be-.patch
        curl -O https://salsa.debian.org/php-team/php/-/raw/debian/main/7.4/debian/patches/0041-Use-libenchant-2-when-available.patch

        patch -p1 < 0040-remove-deprecated-call-and-deprecate-function-to-be-.patch
        patch -p1 < 0041-Use-libenchant-2-when-available.patch

        ./buildconf --force
      fi
    }

    buster_patch
    sid_php74_with_enchant2_patch

    if ! [ -f configure ];then ./buildconf --force; fi

    ./configure ${CONFIGURE}

# make

    make -j "$(nproc)"

    find -type f -name '*.a' -delete

# make install

    $(_sudo) rm -rf ${PHP_PREFIX}

    if [ -d ${PHP_INI_DIR} ];then $(_sudo) mv ${PHP_INI_DIR} ${PHP_INI_DIR}.$( date +%s ).backup; fi

    $(_sudo) make install

    $(_sudo) mkdir -p ${PHP_INI_DIR}/conf.d

    $(_sudo) cp /usr/local/src/php-${PHP_VERSION}/php.ini-development ${PHP_INI_DIR}/php.ini
    $(_sudo) cp /usr/local/src/php-${PHP_VERSION}/php.ini-development ${PHP_INI_DIR}/php.ini-development
    $(_sudo) cp /usr/local/src/php-${PHP_VERSION}/php.ini-production  ${PHP_INI_DIR}/php.ini-production

# php5 not have php-fpm.d

    cd ${PHP_INI_DIR}

    if ! [ -d php-fpm.d ]; then
    # php5
        $(_sudo) mkdir php-fpm.d
        $(_sudo) cp php-fpm.conf.default php-fpm.d/www.conf

    { \
        echo '[global]'; \
        echo "include=${PHP_INI_DIR}/php-fpm.d/*.conf"; \
    } | $(_sudo) tee php-fpm.conf

    else
        $(_sudo) cp php-fpm.d/www.conf.default php-fpm.d/www.conf
        $(_sudo) cp php-fpm.conf.default php-fpm.conf
    fi

    echo "
;;;;;;;;;;;;;;;;;;
; Global Options ;
;;;;;;;;;;;;;;;;;;

[global]

pid = /var/run/php${PHP_NUM}-fpm.pid

error_log = /var/log/php${PHP_NUM}-fpm.error.log

;;;;;;;;;;;;;;;;;;;;
; Pool Definitions ;
;;;;;;;;;;;;;;;;;;;;

[www]

access.log = /var/log/php${PHP_NUM}-fpm.access.log

user = nginx
group = nginx

request_slowlog_timeout = 5
slowlog = /var/log/php${PHP_NUM}-fpm.slow.log

clear_env = no

catch_workers_output = yes

; listen = 9000
; env[APP_ENV] = development

;
; wsl
;

; WSL1 not support listen ip:port
; listen = 127.0.0.1:9000

; WSL1 please use sock
listen = /var/run/php${PHP_NUM}-fpm.sock

listen.owner = nginx
listen.group = nginx
listen.mode = 0660

env[APP_ENV] = wsl

" | $(_sudo) tee ${PHP_INI_DIR}/php-fpm.d/zz-${ID}.conf

}

_install_pecl_ext_by_pickle(){
  export PATH=${PHP_PREFIX}/bin:$PATH
  $(_sudo) chmod 777 $(${PHP_PREFIX}/bin/php-config --extension-dir)

  if [ ${PHP_NUM} -ge "81" ];then set +e; fi

  PICKLE_OPTIONS="-n --php=${PHP_PREFIX}/bin/php -vvv"

  if [ $# -ne 0 ];then
    for extension in $@
    do
      local extension_real_name=$(echo $extension | cut -d "@" -f 2)
      local extension=$(echo $extension | cut -d "@" -f 1)

      $(_sudo) pickle install $extension ${PICKLE_OPTIONS} --defaults

      ${PHP_PREFIX}/bin/php -m > /dev/null 2>&1 \
        || $(_sudo) mv ${PHP_INI_DIR}/conf.d/php-ext-${extension_real_name}.ini \
                       ${PHP_INI_DIR}/conf.d/php-ext-${extension_real_name}.ini.notwork
    done

    $(_sudo) chmod 755 $(${PHP_PREFIX}/bin/php-config --extension-dir)
    set -e

    return
  fi

  echo "--enable-redis-igbinary" > /tmp/redis.configure.options
  echo "--enable-memcached-igbinary" > /tmp/memcached.configure.options

  if [ ${PHP_NUM} -ge "81" ];then
    _install_pecl_ext_by_pickle \
      https://github.com/igbinary/igbinary/archive/master.tar.gz@igbinary \
      https://github.com/phpredis/phpredis/archive/develop.tar.gz@redis \
      https://github.com/xdebug/xdebug/archive/master.tar.gz@xdebug \
      https://github.com/tideways/php-xhprof-extension/archive/master.tar.gz@tideways_xhprof \
      https://github.com/swoole/swoole-src/archive/master.tar.gz@swoole \
      mongodb \
      memcached
  else
    $(_sudo) pickle install igbinary --defaults ${PICKLE_OPTIONS}
    $(_sudo) pickle install redis --defaults ${PICKLE_OPTIONS}
    $(_sudo) pickle install xdebug --defaults ${PICKLE_OPTIONS}
    $(_sudo) pickle install swoole --defaults ${PICKLE_OPTIONS}
    $(_sudo) pickle install memcached --defaults ${PICKLE_OPTIONS}
    $(_sudo) pickle install mongodb --defaults ${PICKLE_OPTIONS}
  fi

  $(_sudo) chmod 755 $(${PHP_PREFIX}/bin/php-config --extension-dir)

  set -e
}

_install_pecl_ext(){
    command -v ${PHP_PREFIX}/bin/pecl && pecl=1 || pecl=0

    $(_sudo) mkdir -p /usr/local/sbin
    $(_sudo) ln -s ${PHP_PREFIX}/bin/php /usr/local/sbin
    $(_sudo) ln -s ${PHP_PREFIX}/bin/phpize /usr/local/sbin
    $(_sudo) ln -s ${PHP_PREFIX}/bin/php-config /usr/local/sbin
    if [ $pecl -eq 0 ];then
      _install_pecl_ext_by_pickle $@

      # $(_sudo) rm -rf /usr/local/sbin/{php,phpize,php-config}
      $(_sudo) rm -rf /usr/local/sbin/php*
      return
    fi

    #
    # https://github.com/docker-library/php/issues/443
    #
    $(_sudo) ${PHP_PREFIX}/bin/pecl update-channels

    PHP_EXTENSION="igbinary \
               redis \
               $( if [ $PHP_NUM = "56" ];then echo "memcached-2.2.0"; else echo "memcached"; fi ) \
               $( if [ $PHP_NUM = "56" ];then echo "xdebug-2.5.5"; else echo "xdebug"; fi ) \
               $( if [ $PHP_NUM = "56" ];then echo "yaml-1.3.1"; else echo "yaml"; fi ) \
               $( if ! [ $PHP_NUM = "56" ];then echo "swoole"; else echo ""; fi ) \
               mongodb"

    if [ $# -ne 0 ];then PHP_EXTENSION=$@;fi

    for extension in ${PHP_EXTENSION}
    do
        echo $extension | tee -a ${PHP_INSTALL_LOG}
        $(_sudo) ${PHP_PREFIX}/bin/pecl install $extension || echo "install $extension error" | tee -a ${PHP_INSTALL_LOG}
    done

    $(_sudo) rm -rf /usr/local/sbin/php*
}

_php_ext_enable(){

echo "date.timezone=${PHP_TIMEZONE:-PRC}" | $(_sudo) tee ${PHP_INI_DIR}/conf.d/date_timezone.ini
echo "error_log=/var/log/php${PHP_NUM}.error.log" | $(_sudo) tee ${PHP_INI_DIR}/conf.d/error_log.ini
echo "session.save_path = \"/tmp\"" | $(_sudo) tee ${PHP_INI_DIR}/conf.d/session.ini

if [ $# -ne 0 ];then
  wsl-php-ext-enable.sh $@

  return
fi
set +e
exts=" pdo_pgsql \
                      xsl \
                      pcntl \
                      shmop \
                      soap \
                      sockets \
                      sysvmsg \
                      sysvsem \
                      sysvshm \
                      calendar \
                      fileinfo \
                      intl \
                      imap \
                      enchant \
                      ldap \
                      pspell \
                      \
                      mongodb \
                      igbinary \
                      redis \
                      memcached \
                      xdebug \
                      $( test $PHP_NUM != '56' && echo 'swoole' ) \
                      opcache \
                      mysqli \
                      $( test $PHP_NUM -ge "74" && echo ffi ) \
                      pgsql \
                      gd "
set -e
for ext in $exts
do
  wsl-php-ext-enable.sh $ext || echo "$ext install error" | tee -a ${PHP_INSTALL_LOG}
done

# config opcache

# echo 'opcache.enable_cli=1' | $(_sudo) tee -a ${PHP_INI_DIR}/conf.d/wsl-php-ext-opcache.ini
echo 'opcache.file_cache=/tmp' | $(_sudo) tee -a ${PHP_INI_DIR}/conf.d/wsl-php-ext-opcache.ini
}

_create_log_file(){

cd /var/log

if ! [ -f php${PHP_NUM}-fpm.error.log ];then $(_sudo) touch php${PHP_NUM}-fpm.error.log ; fi
if ! [ -f php${PHP_NUM}-fpm.access.log ];then $(_sudo) touch php${PHP_NUM}-fpm.access.log ; fi
if ! [ -f php${PHP_NUM}-fpm.slow.log ];then $(_sudo) touch php${PHP_NUM}-fpm.slow.log; fi

$(_sudo) chmod 777 php${PHP_NUM}-*
}

_pickle(){
  # composer global require friendsofphp/pickle
  $(_sudo) curl -sfL -o /usr/local/bin/pickle \
    https://github.com/khs1994-php/pickle/releases/download/nightly/pickle-debug.phar
}

_composer(){
  $(_sudo) curl -sfL -o /usr/local/bin/composer \
    https://getcomposer.org/download/${COMPOSER_VERSION}/composer.phar
#    curl -sfL -o /tmp/installer.php \
#        https://raw.githubusercontent.com/composer/getcomposer.org/cb19f2aa3aeaa2006c0cd69a7ef011eb31463067/web/installer
#
#    # https://github.com/khs1994-docker/lnmp/issues/630
#    $(_sudo) apt show libssl1.1=1.1.0f-3+deb9u2 && $(_sudo) apt install -y --allow-downgrades libssl1.1=1.1.0f-3+deb9u2 || true
#    ${PHP_PREFIX}/bin/php -r " \
#         \$signature = '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5'; \
#         \$hash = hash('sha384', file_get_contents('/tmp/installer.php')); \
#         if (!hash_equals(\$signature, \$hash)) { \
#             unlink('/tmp/installer.php'); \
#             echo 'Integrity check failed, installer is either corrupt or worse.' . PHP_EOL; \
#             exit(1); \
#         }" \
# && $(_sudo) ${PHP_PREFIX}/bin/php /tmp/installer.php --no-ansi --install-dir=${PHP_PREFIX}/bin --filename=composer --version=${COMPOSER_VERSION}
}

################################################################################

_write_version_to_file(){
echo "\`\`\`bash" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

${PHP_PREFIX}/bin/php -v | $(_sudo) tee -a ${PHP_PREFIX}/README.md

echo "\`\`\`" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

echo "\`\`\`bash" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

${PHP_PREFIX}/bin/php -i | grep .ini | $(_sudo) tee -a ${PHP_PREFIX}/README.md

echo "\`\`\`" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

echo "\`\`\`bash" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

${PHP_PREFIX}/sbin/php-fpm -v | $(_sudo) tee -a ${PHP_PREFIX}/README.md

echo "\`\`\`" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

echo "\`\`\`bash" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

cat ${PHP_INSTALL_LOG} | $(_sudo) tee -a ${PHP_PREFIX}/README.md

echo "\`\`\`" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

set +x
for ext in `ls /usr/local/src/php-${PHP_VERSION}/ext`; \
do echo '*' $( ${PHP_PREFIX}/bin/php -r "if(extension_loaded('$ext')){echo '[x] $ext';}else{echo '[ ] $ext';}" ) | $(_sudo) tee -a ${PHP_PREFIX}/README.md ; done
set -x
cat ${PHP_PREFIX}/README.md

}

################################################################################

_tar(){
  rm -rf /tmp/php${PHP_NUM}_ROOT/
  mkdir -p /tmp/php${PHP_NUM}_ROOT/etc

  cd /usr/local/

  cp -a php${PHP_NUM} /tmp/php${PHP_NUM}_ROOT/
  cp -a etc/php${PHP_NUM} /tmp/php${PHP_NUM}_ROOT/etc

  cd /tmp/php${PHP_NUM}_ROOT/

  $(_sudo) tar -zcvf /php${PHP_NUM}.tar.gz .
}

################################################################################

_deb(){

PHP_PKG_VERSION=${PHP_VERSION}

test $PHP_VERSION = 'nightly' && PHP_PKG_VERSION=0.0.0 || true

cd /tmp; $(_sudo) rm -rf khs1994-wsl-php${PHP_NUM}-${PHP_PKG_VERSION} ; mkdir -p khs1994-wsl-php${PHP_NUM}-${PHP_PKG_VERSION}/DEBIAN ; cd khs1994-wsl-php${PHP_NUM}-${PHP_PKG_VERSION}

################################################################################

echo "Package: khs1994-wsl-php${PHP_NUM}
Version: ${PHP_PKG_VERSION}
Prioritt: optional
Section: php
Architecture: amd64
Maintainer: khs1994 <khs1994@khs1994.com>
Bugs: https://github.com/khs1994-docker/lnmp/issues
Depends: $( echo ${PHP_RUN_DEP} | sed "s# #, #g" )
Homepage: https://lnmp.khs1994.com
Description: server-side, HTML-embedded scripting language (default)
 PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used
 open source general-purpose scripting language that is especially suited
 for web development and can be embedded into HTML.

" > DEBIAN/control

echo "#!/bin/bash

# log

cd /var/log

if ! [ -f php${PHP_NUM}.error.log ];then touch php${PHP_NUM}.error.log ; fi
if ! [ -f php${PHP_NUM}-fpm.error.log ];then touch php${PHP_NUM}-fpm.error.log ; fi
if ! [ -f php${PHP_NUM}-fpm.access.log ];then touch php${PHP_NUM}-fpm.access.log ; fi
if ! [ -f php${PHP_NUM}-fpm.slow.log ];then touch php${PHP_NUM}-fpm.slow.log; fi

chmod 777 php${PHP_NUM}*

# bin sbin

for file in \$( ls ${PHP_PREFIX}/bin ); do ln -sf ${PHP_PREFIX}/bin/\$file /usr/local/bin/ ; done

ln -sf ${PHP_PREFIX}/sbin/php-fpm /usr/local/sbin/
" > DEBIAN/postinst

echo "#!/bin/bash
echo
echo \"Meet issue? Please see https://github.com/khs1994-docker/lnmp/issues \"
echo
" > DEBIAN/postrm

echo "#!/bin/bash

if [ -d ${PHP_INI_DIR} ];then
  mv ${PHP_INI_DIR} ${PHP_INI_DIR}.\$( date +%s ).backup
fi

echo -e \"

----------------------------------------------------------------------

Thanks for using khs1994-wsl-php${PHP_NUM} !

Please find the official documentation for khs1994-wsl-php${PHP_NUM} here:
* https://github.com/khs1994-docker/lnmp/tree/master/wsl

Meet issue? please see:
* https://github.com/khs1994-docker/lnmp/issues

----------------------------------------------------------------------

\"
" > DEBIAN/preinst

################################################################################

chmod -R 755 DEBIAN ; mkdir -p usr/local/etc

$(_sudo) cp -a ${PHP_PREFIX} usr/local/php${PHP_NUM} ; $(_sudo) cp -a ${PHP_INI_DIR} usr/local/etc/

cd ..

DEB_NAME=khs1994-wsl-php${PHP_NUM}_${PHP_PKG_VERSION}-${ID}-$( lsb_release -cs )_amd64.deb

$(_sudo) dpkg-deb -b khs1994-wsl-php${PHP_NUM}-${PHP_PKG_VERSION} $DEB_NAME

$(_sudo) cp -a /tmp/${DEB_NAME} /

echo "\$ $(_sudo) dpkg -i ${DEB_NAME}"

$(_sudo) rm -rf $PHP_PREFIX ; $(_sudo) rm -rf $PHP_INI_DIR

$(_sudo) dpkg -i /${DEB_NAME}

# test

test $host = 'x86_64-linux-gnu'  && _test

}

################################################################################

if [ -z "$1" ];then _print_help_info ; else PHP_VERSION=$1 ; fi

set -ex

$(_sudo) apt update

command -v wget > /dev/null || $(_sudo) apt install wget -y

mkdir -p /tmp/php-builder

test "$PHP_VERSION" = 'apt' && PHP_VERSION=7.4.13
test "$PHP_VERSION" = 'apt-dev' && PHP_VERSION=7.4.13

_get_phpnum $PHP_VERSION

export PHP_PREFIX=/usr/local/php${PHP_NUM}

export PHP_INI_DIR=/usr/local/etc/php${PHP_NUM}

test $host = 'aarch64-linux-gnu' && \
              export PHP_PREFIX=/usr/local/arm64/php${PHP_NUM} \
                     PHP_INI_DIR=/usr/local/arm64/etc/php${PHP_NUM}

test $host = 'arm-linux-gnueabihf' && \
              export PHP_PREFIX=/usr/local/arm32/php${PHP_NUM} \
                     PHP_INI_DIR=/usr/local/arm32/etc/php${PHP_NUM}

# verify os

. /etc/os-release

#
# ID=debian
# VERSION_ID="9"
#
# ID=ubuntu
# VERSION_ID="16.04"
#

# debian9 notsupport php56

if [ "$ID" = 'debian' ] && [ "$VERSION_ID" = "9" ] && [ $PHP_NUM = "56" ];then \
  echo "debian9 notsupport php56" ; exit 1 ; fi

$(_sudo) apt install -y libargon2-0-dev > /dev/null 2>&1 || export ARGON2=false

if [ "$ID" = 'debian' ] && [ "$VERSION_ID" = "9" ];then
##<argon2>##
  sed -e 's/stretch/buster/g' /etc/apt/sources.list | $(_sudo) tee /etc/apt/sources.list.d/buster.list; \
  { \
    echo 'Package: *'; \
    echo 'Pin: release n=buster'; \
    echo 'Pin-Priority: -10'; \
    echo; \
    echo 'Package: libargon2*'; \
    echo 'Pin: release n=buster'; \
    echo 'Pin-Priority: 990'; \
  } | $(_sudo) tee /etc/apt/preferences.d/argon2-buster

  $(_sudo) apt update
  $(_sudo) apt install -y --no-install-recommends libargon2-dev
  export ARGON2=true
fi

$(_sudo) apt install -y curl

command -v /usr/local/bin/pickle > /dev/null || _pickle
command -v /usr/local/bin/composer > /dev/null || _composer

$(_sudo) chmod +x /usr/local/bin/pickle /usr/local/bin/composer

if [ "$2" = 'enable-ext' ];then
  ( shift 2 ; _install_pecl_ext $@; _php_ext_enable $@; _create_log_file ; \
  ( test $host = 'x86_64-linux-gnu'  && \
  _test \
  ${PHP_PREFIX}/bin/php-config | $(_sudo) tee -a ${PHP_INSTALL_LOG} \
  ) ; _write_version_to_file )

  exit
fi

_install_php_run_dep

if [ "$1" = 'apt' ];then exit 0;fi
if [ "$1" = 'apt-dev' ];then _install_php_build_dep ; exit $? ; fi

_install_php_build_dep

for command in "$@"
do
  test $command = '--skipbuild' && export SKIP_BUILD=1
  test $command = '--ci'        && export PHP_URL=https://www.php.net/distributions
done

test "${SKIP_BUILD}" != 1 &&  \
    ( _download_src ; \
      _builder ; \
      _install_pecl_ext ; \
      _php_ext_enable ; \
      _create_log_file ; \
    ( test $host = 'x86_64-linux-gnu'  && \
    _test ; \
    ${PHP_PREFIX}/bin/php-config | $(_sudo) tee -a ${PHP_INSTALL_LOG} \
    ) ; \
    _write_version_to_file )

for command in "$@"
do
  test $command = 'tar' && _tar
  test $command = 'deb' && _deb
done

ls -lah /*.tar.gz /*.deb || true
